using OpenQA.Selenium.Edge;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using System.Threading;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Remote;
using System.IO;
using System.Configuration;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;

namespace SendEmail
{
    class Program
    {
        static string GetFile(string dirPath)
        {
            DirectoryInfo d = new DirectoryInfo(dirPath);
            FileSystemInfo[] fsinfos = d.GetFileSystemInfos();
            DateTime latestModifyTime = DateTime.MinValue;
            string res = "";
            foreach (FileSystemInfo fsinfo in fsinfos)
            {
                if (fsinfo.Name.Contains(".zip"))
                {
                    if (latestModifyTime <= fsinfo.LastWriteTime)
                    {
                        res = fsinfo.FullName;
                        latestModifyTime = fsinfo.LastWriteTime;
                    }

                }
            }
            return res;
        }
        static void Main(string[] args)
        {
            var dirPath = ConfigurationManager.AppSettings["FileDic"];
            string filePath = GetFile(dirPath);
            if (filePath == "")
            {
                Console.WriteLine("没有找到文件");
            }
            var fromEmailUser = "fromUser";
            var password = "password";
            var toEmailAddress = "toEmail@qq.com";

            EdgeDriverService service = EdgeDriverService.CreateDefaultService(@".\", "msedgedriver.exe");
            EdgeOptions option = new EdgeOptions();
            option.BinaryLocation = @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
    
            var driver = new EdgeDriver(service, option);
            var mail_url = "https://www.mail.163.com";
            driver.Url = mail_url;
            driver.Navigate();
            try
            {
                var oldJsonStr = File.ReadAllText("cookies.json");
                var oldCookies = JArray.Parse(oldJsonStr);


                
               
                foreach (var cookie in oldCookies)
                {
                    var newCookie = new Cookie(cookie["name"].ToString(), cookie["value"].ToString(), cookie["domain"].ToString(), cookie["path"].ToString(), DateTime.Today.AddDays(10));
                    driver.Manage().Cookies.AddCookie(newCookie);
                }
                driver.Url = mail_url;
                driver.Navigate();
                Thread.Sleep(5000);
            }
            catch
            {

            }
            
            try
            {
                var loginInfo = driver.FindElement(By.XPath("/html/body/header/div[1]/ul[1]/li[1]/div/span[1]"));
            }
            catch
            {
                driver.SwitchTo().Frame(driver.FindElement(By.TagName("iframe")));
                // 定位账号输入框
                driver.FindElement(By.XPath("//input[@name=\"email\"]")).Clear();  // 删除提示信息
                driver.FindElement(By.XPath("//input[@name=\"email\"]")).SendKeys(fromEmailUser);   // 测试过程中替换成自己的账号名就可以
                driver.FindElement(By.Name("password")).SendKeys(password);   // 测试过程中替换成自己的账号名就可以
                driver.FindElement(By.Id("dologin")).Click();

                var cookies = driver.Manage().Cookies.AllCookies;
                string jsStr = Newtonsoft.Json.JsonConvert.SerializeObject(cookies);
                FileStream fileStream = new FileStream("cookies.json", FileMode.Create);
                byte[] buffer = Encoding.UTF8.GetBytes(jsStr);
                fileStream.Write(buffer, 0, buffer.Length); ;
            }
            Thread.Sleep(5000);


            // 点击写邮件按钮
            driver.ExecuteScript("$(\"#_mail_component_76_76\").click()");
            Thread.Sleep(5000);
            Actions action = new Actions(driver);
            // 添加收件人
            action.MoveToElement(driver.FindElement(By.XPath("/html/body/div[2]/div[1]/div[2]/div[1]/section/header/div[1]/div[1]/div/div[2]")))
                .Click().Pause(TimeSpan.FromSeconds(2))
                .SendKeys(toEmailAddress).Pause(TimeSpan.FromSeconds(3)).Perform();
            Thread.Sleep(1000);
            // 添加主题
            action.MoveToElement(driver.FindElement(By.XPath("/html/body/div[2]/div[1]/div[2]/div[1]/section/header/div[2]/div[1]/div/div/input"))).DoubleClick().Pause(TimeSpan.FromSeconds(3)).SendKeys("主题-Data").Perform();
            
            // 添加附件
            action.MoveToElement(driver.FindElement(By.XPath("/html/body/div[2]/div[1]/div[2]/div[1]/section/header/div[3]/div[1]/div[2]/input"))).Click().Perform();
            Thread.Sleep(5000);
            var dialog = Win32API.FindWind("打开");
            var openButton = Win32API.FindWindowEx(dialog, IntPtr.Zero, null, "打开");
            var ComboBoxEx32 = Win32API.FindWindowEx(dialog, IntPtr.Zero, "ComboBoxEx32", "");
            var ComboBox = Win32API.FindWindowEx(ComboBoxEx32, IntPtr.Zero, "ComboBox", "");
            var edit = Win32API.FindWindowEx(ComboBox, IntPtr.Zero, "Edit", "");
            var button = Win32API.FindWindowEx(dialog, IntPtr.Zero, "Button", "");
            Win32API.SendMessage(edit, Win32Const.WM_SETTEXT, IntPtr.Zero, filePath);
            Win32API.SendMessage(dialog, Win32Const.WM_COMMAND, (IntPtr)1, button);

            // 添加邮件内容
            driver.SwitchTo().Frame(driver.FindElement(By.XPath("//iframe[contains(@class,'APP-editor-iframe')]")));
            driver.FindElement(By.XPath("/html/body")).SendKeys("xxx");
            driver.SwitchTo().DefaultContent();

            // 等待上传
            for (var i = 0; i < 100; i++)
            {
                Thread.Sleep(2000);
                try
                {
                    var uploadElement = driver.FindElement(By.ClassName("nui-txt-suc"));

                    if (uploadElement != null)
                    {
                        break;
                    }
                }
                catch
                {

                }

            }

            // 点击发送
            var toEdit = driver.FindElement(By.XPath("/html/body/div[2]/div[1]/div[2]/header/div/div[1]/div/span[2]"));
            action.MoveToElement(toEdit).Click().Perform();
            Thread.Sleep(5*1000);

            driver.Close();
            driver.Dispose();
            Process.GetCurrentProcess().CloseMainWindow();
        }
    }
}
